package javacommon.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.filter.OncePerRequestFilter;

import com.smg.community.model.SmgMemberCoor;
import com.smg.community.service.SmgMemberCoorManager;
import com.smg.community.util.StringUtil;


public class LogFilter  extends OncePerRequestFilter implements Filter {
	
	private static ApplicationContext ac;
	
	private static SmgMemberCoorManager smgMemberCoorManager;
	
	Log logger = LogFactory.getLog(LogFilter.class);

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		logger.debug("in logfilter"+request.getRequestURI());
		logger.debug("in logfilter"+request.getRequestURL());
		String memberId = request.getParameter("memberId");
		String gpsLongitude = request.getParameter("gpsLongitude");
		String gpsLatitude = request.getParameter("gpsLatitude");
		if ( ac == null ){
			ac = ContextLoader.getCurrentWebApplicationContext();
			smgMemberCoorManager = (SmgMemberCoorManager)ac.getBean("smgMemberCoorManager");
		 }
		if ( !StringUtil.isEmpty(memberId) &&   !StringUtil.isEmpty(gpsLongitude)   &&   !StringUtil.isEmpty(gpsLatitude) && !"0".equals(memberId)  ){
			SmgMemberCoor memberCoor = new SmgMemberCoor();
			try {
				memberCoor.setMemberId(Integer.parseInt(memberId));
				memberCoor.setGpsLatitude(Float.parseFloat(gpsLatitude));
				memberCoor.setGpsLongitude(Float.parseFloat(gpsLongitude));
				smgMemberCoorManager.save(memberCoor);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		filterChain.doFilter(request, response);
	}

}
